package com.hq.ims.data.aop;

import com.hq.ims.data.utils.CurThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 初始化aop
 * 描述: 第一个进入的切面初始化ThreadStore
 */
@Order(1)
@Aspect
@Component
@Slf4j
public class InitAspect {

    @Pointcut(value = "execution(* com.hq.ims..controller.*.*(..))")
    private void controllerAspect() {
    }

    @Before(value = "controllerAspect()")
    public void doBefore(JoinPoint point) throws Throwable {
        CurThreadLocalUtil.getInstance().remove();
        CurThreadLocalUtil.ThreadStore threadStore = CurThreadLocalUtil.getInstance().get();
        if (threadStore == null) {
            threadStore = new CurThreadLocalUtil.ThreadStore();
            CurThreadLocalUtil.getInstance().bind(threadStore);
        }
        //清除数据
        threadStore.clear();
    }

    @After(value = "controllerAspect()")
    public void doAfter(JoinPoint point) {
        CurThreadLocalUtil.ThreadStore threadStore = CurThreadLocalUtil.getInstance().get();
        if (threadStore != null) {
            threadStore.clear();
        }
    }
}
